/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2022-12-06
 * Time:8:46
 */
class Counter{
    public int a=0;
    synchronized public void add(){
        a++;
    }

}
public class ThreadDemo1 {
    public static void main1(String[] args) {
        Counter counter=new Counter();
        Thread t1=new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        Thread t2=new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        t1.start();
        t2.start();
        try {
            t2.join();
            t1.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(counter.a);
    }
    //死锁
    //最简单的解锁办法就是，先用最近的且最小的，
    public static void main(String[] args) {
        Object left=new Object();
        Object right=new Object();
        Thread A=new Thread(()->{
           synchronized(right){
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
               synchronized (left){
                   System.out.println("left");
               }
            };

        });
        Thread B=new Thread(()->{
            synchronized(left){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (right){
                    System.out.println("right");
                }
            };
        });
        A.start();
        B.start();
    }
}
